from logging import getLogger

from zope.interface import Interface, implements
from zope.configuration import config, fields
from zope.schema import TextLine

from meercat.mapreduce.registry import register_mapper
from meercat.mapreduce.mappers import xsl



log = getLogger('meercat.mapreduce.zcml')

class IMapper(Interface):
    factory = fields.GlobalObject(
        title=u'Mapper factory',
        description=u'The factory that creates the mapper',
        required=True)

class IXslMapper(IMapper):
    factory = fields.GlobalObject(
        title=u'XSL Mapper factory',
        description=u'The factory that creates the xsl mapper',
        required=False)

class ITransform(Interface):
    source = TextLine(
        title=u'Source format',
        description=u'The source format for the transform',
        required=True)
    
    destination = TextLine(
        title=u'Destination format',
        description=u'The destination format for the transform',
        required=True)

class IXslFile(ITransform):
    file = fields.Path(
        title=u'XSL File',
        description=u'The XSL file for the transform',
        required=True)

def transformHandler(context, source, destination):
    log.debug('transformHandler(%s, %s, %s)' % (str(context), str(source),
                                               str(destination),))
    
    context._formats.append((source, destination))

def xslFileHandler(context, source, destination, file):
    log.debug('xslFileHandler(%s, %s, %s, %s)' % (str(context),str(source),
                                                 str(destination),str(file),))
    context._formats.append((source, destination, file))

class BasicMapper(config.GroupingContextDecorator):
    implements(config.IConfigurationContext, IMapper)
    
    def __init__(self, context, factory):
        log.debug('%s.__init__(%s, %s)' % (str(self),str(context),str(factory),))
        self.context = context
        self._factory = factory
        self._formats = []
    
    def before(self):
        log.debug('%s.before()' % (str(self),))
        super(BasicMapper,self).before()
    
    def after(self):
        log.debug('%s.after()' % (str(self),))
        super(BasicMapper,self).after()
        if len(self._formats) == 0:
            self._formats = None
        
        register_mapper(self._factory(self._formats))
    
class XslMapper(BasicMapper):
    implements(IXslMapper)
    
    def __init__(self, context, factory=None):
        log.debug('%s.__init__(%s, %s)' % (str(self),str(context),str(factory),))
        if factory is None:
            factory = xsl.XslMapper
        
        super(XslMapper, self).__init__(context, factory)
    
    def after(self):
        log.debug('%s.after()' % (str(self),))
        log.info(str(self._factory(*self._formats)))
        register_mapper(self._factory(*self._formats))
